package com.ssm.common.http;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * https://blog.csdn.net/f641385712/article/details/100713622
 * https://blog.csdn.net/f641385712/article/details/100753981
 */
@Component
public class TestHttpClient {
    @Value("${http.url:http://www.baidu.com}")
    private String tokrnURL;

    private RestTemplate restTemplate;

    {
        HttpComponentsClientHttpRequestFactory clientFactory = new HttpComponentsClientHttpRequestFactory();
        clientFactory.setConnectTimeout(5000);
        clientFactory.setReadTimeout(5000);
        // 使用 apache httpclient
        restTemplate = new RestTemplate(clientFactory);
        // 身份认证
        BasicAuthenticationInterceptor interceptor = new BasicAuthenticationInterceptor("admin", "123456");
        restTemplate.setInterceptors(Collections.singletonList(interceptor));
    }

    public Object authLogin() {
        Map<String, Object> map = new HashMap<>();
        map.put("username", "admin");
        map.put("password", "123456");
        Object response = restTemplate.postForObject(tokrnURL, map, Object.class);
        System.out.println(response);
        return response;
    }

    private Object postMessage(Object request, String token, String url) {
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.APPLICATION_JSON);
        header.set("Authentication-Info", token);
        HttpEntity<Object> httpEntity = new HttpEntity<>(request, header);
        Object response = restTemplate.postForObject(url, httpEntity, Object.class);
        System.out.println(response);
        return response;
    }
}
